//
//  SKCoreData.m
//  Sudoku
//
//  Created by Richard Hodgkins on 08/09/2012.
//  Copyright (c) 2012 Richard Hodgkins. All rights reserved.
//

#import "SKCoreData.h"

#import "SKBoard+Helper.h"

@implementation SKCoreData

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

+ (SKCoreData *)sharedInstance
{
    static SKCoreData *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[SKCoreData alloc] init];
    });
    return sharedInstance;
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            ALog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } else {
            DLog(@"Saved changes to core data");
        }
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Sudoku" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Sudoku.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        
        ALog(@"Unresolved error %@, %@", error, [error userInfo]);
        
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         */
        if ([[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]) {
            
            [SKCoreData addInitialData];
                
            return [self persistentStoreCoordinator];
        }
        
         /*
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         */
        abort();
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

#define INITIAL_DATA_FILENAME @"boards"
#define INITIAL_DATA_TYPE @"json"

#define JSON_ID @"id"
#define JSON_NAME @"name"
#define JSON_RATING @"rating"
#define JSON_DIFFICULTY @"difficulty"
#define JSON_BOARD @"board"

+ (void) addInitialData
{
    if (USE_TEST_DATA) {
        
        DLog(@"Adding test data");
        SInt8 *layout = (SInt8 *) malloc(SIZE_OF_LAYOUT * sizeof(SInt8));
        for (uint i=0;i<SIZE_OF_LAYOUT;i++) {
            layout[i] = (((i / 9) + i) % 9) + 1;
            if (layout[i] == 1 && i > 45) {
                layout[i] = -layout[i];
            }
        }
        
        [SKBoard insertBoard:1 withName:@"Board1Easy" withDifficulty:SKBoardDifficultyEasy withRating:0 withLayout:layout];
        [SKBoard insertBoard:2 withName:@"Board2Easy" withDifficulty:SKBoardDifficultyEasy withRating:0 withLayout:layout];
        [SKBoard insertBoard:3 withName:@"Board3Easy" withDifficulty:SKBoardDifficultyEasy withRating:0 withLayout:layout];
        [SKBoard insertBoard:4 withName:@"Board4Easy" withDifficulty:SKBoardDifficultyEasy withRating:0 withLayout:layout];
        
        [SKBoard insertBoard:5 withName:@"Board1Hard" withDifficulty:SKBoardDifficultyHard withRating:3.5 withLayout:layout];
        [SKBoard insertBoard:6 withName:@"Board2Hard" withDifficulty:SKBoardDifficultyHard withRating:3.5 withLayout:layout];
        [SKBoard insertBoard:7 withName:@"Board3Hard" withDifficulty:SKBoardDifficultyHard withRating:3.5 withLayout:layout];
        [SKBoard insertBoard:8 withName:@"Board4Hard" withDifficulty:SKBoardDifficultyHard withRating:3.5 withLayout:layout];
        
        [SKBoard insertBoard:9 withName:@"Board1Medium" withDifficulty:SKBoardDifficultyMedium withRating:2 withLayout:layout];
        [SKBoard insertBoard:10 withName:@"Board2Medium" withDifficulty:SKBoardDifficultyMedium withRating:2 withLayout:layout];
        [SKBoard insertBoard:11 withName:@"Board3Medium" withDifficulty:SKBoardDifficultyMedium withRating:2 withLayout:layout];
        [SKBoard insertBoard:12 withName:@"Board4Medium" withDifficulty:SKBoardDifficultyMedium withRating:2 withLayout:layout];
        
        free(layout);
    } else {
        
        DLog(@"Adding initial data");
        
        // Get and open initial data file
        NSString *jsonFile = [[NSBundle mainBundle] pathForResource:INITIAL_DATA_FILENAME ofType:INITIAL_DATA_TYPE];
        NSInputStream *jsonFileStream = [NSInputStream inputStreamWithFileAtPath:jsonFile];
        [jsonFileStream open];
        
        // Parse file into JSON
        NSError *error;
        NSArray *json = [NSJSONSerialization JSONObjectWithStream:jsonFileStream options:0 error:&error];
        
        [jsonFileStream close];
        jsonFileStream = nil;
        
        if (error) {
            ALog(@"An error occurred when reading JSON boards file: %@", error);
        } else {
            
            for (NSDictionary *boardJson in json) {
                NSInteger boardId = [[boardJson objectForKey:JSON_ID] intValue];
                NSString *name = [boardJson objectForKey:JSON_NAME];
                SKBoardDifficulty difficulty =[[boardJson objectForKey:JSON_DIFFICULTY] integerValue];
                float rating = [[boardJson objectForKey:JSON_RATING] floatValue];
                NSArray *layoutArray = [boardJson objectForKey:JSON_BOARD];
                
                SInt8 *layout = (SInt8 *) malloc(SIZE_OF_LAYOUT * sizeof(SInt8));
                for (uint i=0; i<SIZE_OF_LAYOUT; i++) {
                    layout[i] = (SInt8) [[layoutArray objectAtIndex:i] intValue];
                }
                
                [SKBoard insertBoard:boardId withName:name withDifficulty:difficulty withRating:rating withLayout:layout];
            }
        }
    }
    
#ifdef DEBUG
    [[SKCoreData sharedInstance] saveContext];
#endif
}

@end
